<!--
 * @Author: Lizhenyu
 * @Date: 2021-07-22 14:36:53
 * @FilePath: \usp-osm-frondend\src\views\couponsCenter\couponMgmt\import\fileImport.vue
-->
<template>
  <div class="source" v-loading="pageLoading" element-loading-text="加载中...">
    <v-notes>
      <el-form
        label-width="160px"
        :model="couponForm"
        ref="searchForm"
        class="search-form"
        size="small"
      >
        <el-row class="search-row">
          <el-col :span="24">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="券池编码" prop="couponCode">
                  <el-input
                    placeholder="券池编码"
                    v-model="couponForm.couponCode"
                    disabled
                    clearable
                    @keyup.enter.native.prevent="searchService"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="券池名称" prop="couponName">
                  <el-input
                    placeholder="券池名称"
                    v-model="couponForm.couponName"
                    disabled
                    clearable
                    @keyup.enter.native.prevent="searchService"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
    </v-notes>
    <div class="mb-lg">
      <v-table
        :data="tableData"
        ref="multipleTable"
        :listLoading="listLoading"
        :loadingText="loadingText"
        :paginationTotal="total"
        v-on:pageSizeChange="pageSizeChange"
        v-on:currentPageChange="currentPageChange"
        border
        pagination
      >
        <div slot="header">
          <el-button
            @click="importFile"
            class="dark-btn"
            style="margin-bottom: 0 !important"
          >
            导入
          </el-button>
          <el-button
            @click="exportFile"
            class="dark-btn"
            style="margin-bottom: 0 !important"
          >
            下载模板
          </el-button>
        </div>
        <el-table-column
          label="文件名"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.fileName }}
          </template>
        </el-table-column>
        <el-table-column
          label="上传时间"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime | timestampToChange('time') }}
          </template>
        </el-table-column>
        <el-table-column
          label="导入数量"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ scope.row.exportQuantity }}
          </template>
        </el-table-column>
        <el-table-column
          label="处理状态"
          align="center"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{ getDictionaryNameByCode('IMPORTSTATE', scope.row.state) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          fixed="right"
          min-width="110"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.state === '3'" class="colorLink" @click="checkFailInfo(scope.row)">查看失败信息</span>
          </template>
        </el-table-column>
      </v-table>
    </div>
    <!-- 导入文件 -->
    <el-dialog
      title="上传文件"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :wrapperClosable="false"
      :element-loading-text="$t('loading')"
      width="400px"
      append-to-body
      top="0"
    >
      <el-upload
        class="upload-demo"
        ref="upload"
        :on-success="uploadSuccess"
        :on-change="handleChange"
        :on-error="uploadError"
        :headers="myHeaders"
        :file-list="fileList"
        drag
        :data="importData"
        :action="uploadAddr"
        :limit="1"
        :on-exceed="handleExceed"
        :auto-upload="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          允许的类型：XLS, XLSX, CSV.
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button class="search-btn" size="small" @click="submitFile">
          提交
        </el-button>
        <el-button
          class="reset-btn"
          size="small"
          @click="dialogVisible = false"
        >
          取消
        </el-button>
      </div>
    </el-dialog>
    <!-- 查看失败信息 -->
    <el-dialog
      title="查看失败信息"
      append-to-body
      :visible.sync="failInfoShow"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :wrapperClosable="false"
      destroy-on-close
      top="0"
      width="60%"
    >
      <div class="failInfo" v-loading="dialogLoading">
        <el-row style="padding-bottom: 10px;" v-for="(item, index) in failList" :key="index">
          <el-col :span="6" :offset="6">
            <span>{{ item.couponNo }}</span>
          </el-col>
          <el-col :span="6">
             <span style="text-align: center;">{{ getDictionaryNameByCode('IMPORTFAILSTATE', item.importDescription) }}</span>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" style="text-align: right">
        <el-button @click="failInfoShow = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { setRouterParams, getRouterParams } from '@/utils/auth'
import { getCouponDetail, getCouponTempList, checkFailInfo } from '@/api/coupon'
import Vue from 'vue'
import { ACCESS_TOKEN, USERID } from '@/config/variableInit'
import VNotes from '@/components/Notes/index'
import VTable from '@/components/PageTable/index'
import { common } from '@/mixins/common'
import { mapGetters } from 'vuex'
export default {
  name: 'couponList',
  components: {
    VNotes,
    VTable
  },
  mixins: [common],
  data () {
    return {
      id: '',
      tableData: [],
      showContent: false,
      pageLoading: false,
      dialogVisible: false,
      failInfoShow: false,
      fileList: [],
      importData: {},
      myHeaders: { Authorization: Vue.ls.get(ACCESS_TOKEN), userId: Vue.ls.get(USERID), state: 'state' },
      uploadAddr: process.env.VUE_APP_BASE_URL + '/admin/promotion/couponImport/importTemplate',
      failList: [],
      couponForm: {
        couponCode: '',
        couponName: '',
        couponId: '',
        displayStart: 0, // 开始查询条数
        displayLength: 10 // 每页展示条数
      },
      dialogLoading: false,
      selectData: [],
      listLoading: false,
      loadingText: '加载中...',
      total: 0,
      pageSize: 10,
      currentPage: 1
    }
  },
  computed: {
    ...mapGetters(['lookupItems', 'roles'])
  },
  created () {
  },
  mounted () {
    let params = {}
    if (this.$route.params.id) {
      setRouterParams(this.$route)
      params = this.$route.params
    } else {
      params = getRouterParams(this.$route)
    }
    this.id = params.id
    this.getDetails(this.id)
  },
  methods: {
    getDetails (id) {
      const params = {
        id: id
      }
      getCouponDetail(params).then((res) => {
        if (res) {
          if (Number(res.code) === 1) {
            this.couponForm.couponCode = res.obj.couponCode
            this.couponForm.couponName = res.obj.couponName
            this.importData.couponId = res.obj.id
            this.fetchList()
          } else {
            this.$alert('券池信息获取失败')
          }
        }
      })
    },
    searchService () {
      this.couponForm.displayStart = 0
      this.$refs.multipleTable.restPage()
      this.fetchList()
    },
    fetchList () {
      if (
        !this.$auth('serviceRightsConfigurationCenter:serviceManagement:list')
      ) {
        this.$alert('您没有权限')
        return false
      }
      this.listLoading = true
      const params = {
        ...this.couponForm,
        couponId: this.id
      }
      getCouponTempList(params).then((res) => {
        this.listLoading = false
        if (res) {
          if (Number(res.code) === 1) {
            const obj = res.obj
            this.tableData = obj.data || []
            this.total = obj.total
          } else if (Number(res.code) === 0) {
            this.$confirm(res.msg, {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          } else {
            this.$confirm(this.$t(res.code), {
              confirmButtonText: '确定',
              showCancelButton: false
            })
          }
        }
      })
    },
    resetForm (formName) {
      this.couponForm.displayStart = 0
      this.couponForm.displayLength = 10
      this.searchService()
    },
    pageSizeChange (size) {
      this.couponForm.displayLength = size
      this.fetchList()
    },
    currentPageChange (curPage) {
      this.couponForm.displayStart = curPage - 1
      this.fetchList()
    },
    importFile () {
      this.dialogVisible = true
    },
    exportFile () {
      // this.listLoading = true
      this.$download('/admin/promotion/couponList/downloadTemplate', {}, 'get')
    },
    checkFailInfo (row) {
      this.failInfoShow = true
      this.dialogLoading = true
      const params = {
        id: row.id
      }
      checkFailInfo(params).then(res => {
        if (res) {
          this.dialogLoading = false
          if (Number(res.code) === 1) {
            this.failList = res.obj
          }
        }
      })
    },
    upload () {
      this.dialogVisible = true
    },

    submitFile () {
      this.$refs.upload.submit()
    },

    // 上传之前回调
    handleChange (file, fileList) {
      // 文件类型判断
      const fileTypeReg = /\.(xls|xlsx|csv)/
      if (!fileTypeReg.test(file.name)) {
        this.fileList = fileList.filter((item) => item !== file)
        this.$alert('文件无法上传：文件类型无效。')
      }
    },

    // 超出限制上传个数提示
    handleExceed () {
      this.$alert('超出文件个数限制。')
    },

    // 上传成功提示
    uploadSuccess () {
      this.$confirm(('上传成功'), {
        confirmButtonText: '确定',
        showCancelButton: false
      })
      this.dialogVisible = false
      this.fetchList(this.id)
      this.$refs.upload.clearFiles()
    },

    // 上传失败提示
    uploadError () {
      this.dialogVisible = false
      this.$alert('上传失败')
    }
  }
}
</script>

<style>
</style>
